<?php

function my_query_vars($vars) {
    // these values should match those in the rewrite rule query string above
    // I recommend using something more unique than 'action' and 'show', as you
    // could collide with other plugins or WordPress core
    $my_vars = array(
        'slug_gallery',
        'album_id',
        'page',
    );

    return array_merge($my_vars, $vars);
}

function vn_str_filter ($str){
    $unicode = array(
        'a'=>'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ',
        'd'=>'đ',
        'e'=>'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ',
        'i'=>'í|ì|ỉ|ĩ|ị',
        'o'=>'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ',
        'u'=>'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự',
        'y'=>'ý|ỳ|ỷ|ỹ|ỵ',
        'A'=>'Á|À|Ả|Ã|Ạ|Ă|Ắ|Ặ|Ằ|Ẳ|Ẵ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ',
        'D'=>'Đ',
        'E'=>'É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ',
        'I'=>'Í|Ì|Ỉ|Ĩ|Ị',
        'O'=>'Ó|Ò|Ỏ|Õ|Ọ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ',
        'U'=>'Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự',
        'Y'=>'Ý|Ỳ|Ỷ|Ỹ|Ỵ',
    );
    
   foreach($unicode as $nonUnicode=>$uni){
        $str = preg_replace("/($uni)/i", $nonUnicode, $str);
   }
    return $str;
}

function get_id_by_slug($slug, $type, $id = 0) {

    global $wpdb;

    switch ($type) {
        case 'image':
            $check_sql = "SELECT pid FROM $wpdb->nggpictures WHERE image_slug = %s AND NOT pid = %d LIMIT 1";
            break;
        case 'album':
            $check_sql = "SELECT id FROM $wpdb->nggalbum WHERE slug = %s AND NOT id = %d LIMIT 1";
            break;
        case 'gallery':
            $check_sql = "SELECT gid FROM $wpdb->nggallery WHERE slug = %s AND NOT gid = %d LIMIT 1";
            break;
        default:
            return false;
    }

    //if you didn't give us a name we take the type
    $slug = empty($slug) ? $type : $slug;

    // Slugs must be unique across all objects.
    $result = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $id));

    return $result;
}

add_filter('query_vars', 'my_query_vars');

if (function_exists('add_theme_support')) {
    add_theme_support('post-thumbnails');
}
// Set path to Slope Framework and theme specific functions
$admin_path = TEMPLATEPATH . '/admin-functions/';
$include_path = TEMPLATEPATH . '/stInclude/';
require_once $include_path . '/libs/functions/core.php';
require_once $include_path . '/libs/classes/stthemehook.php';
require_once $include_path . '/libs/classes/stthemefunctions.php';
require_once $include_path . '/libs/classes/stthememodel.php';
require_once $include_path . '/libs/classes/stthemeview.php';
require_once $include_path . '/libs/classes/stwidgets.php';

// Add hook function
$config = include $include_path . 'config.php';
if (is_admin()) {
    require_once ($admin_path . 'admin.php');
} else {
    require_once $admin_path . 'hook.php';
    $hook = new hooks($config);
}
do_action($config['theme_name'] . '_extra_contruction');

add_theme_support('post-formats', array('aside', 'image', 'link', 'quote', 'status'));


/* pagination */
remove_action('woocommerce_pagination', 'woocommerce_pagination', 10);

function woocommerce_pagination() {
    wp_paginate();
}

add_action('woocommerce_pagination', 'woocommerce_pagination', 10);


/* add to cart js */
//wp_dequeue_script('wc-add-to-cart');
wp_dequeue_script('wc-add-to-cart-variation');
//wp_enqueue_script('wc-add-to-cart', get_bloginfo('stylesheet_directory') . '/js/woo/my-add-to-cart.js', array('jquery'), false, true);
wp_enqueue_script('wc-add-to-cart-variation', get_bloginfo('stylesheet_directory') . '/js/woo/add-to-cart-variation.js', array('jquery'), false, true);


/**
 * Product Summary Box
 *
 * @see woocommerce_template_single_title()
 * @see woocommerce_template_single_price()
 * @see woocommerce_template_single_excerpt()
 * @see woocommerce_template_single_meta()
 * @see woocommerce_template_single_sharing()
 */
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 5);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_sharing', 50);
//	remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );

add_action('woocommerce_single_product_excerpt', 'woocommerce_template_single_excerpt', 20);

/* * *********** TIEN TE VND ************* */

add_filter('woocommerce_currencies', 'add_my_currency');

function add_my_currency($currencies) {
    $currencies['Đồng'] = __('Viet Nam Dong', 'woocommerce');
    return $currencies;
}

add_filter('woocommerce_currency_symbol', 'add_my_currency_symbol', 10, 2);

function add_my_currency_symbol($currency_symbol, $currency) {
    switch ($currency) {
        case 'Đồng': $currency_symbol = '';
            break;
    }
    return $currency_symbol;
}

/* * *************** NEXT & PREVIOUS PRODUCT LINK *********** */

function next_post_link_product($format = '%link &raquo;', $link = '%title', $in_same_cat = false, $excluded_categories = '') {
    adjacent_post_link_product($format, $link, $in_same_cat, $excluded_categories, false);
}

function previous_post_link_product($format = '&laquo; %link', $link = '%title', $in_same_cat = false, $excluded_categories = '') {
    adjacent_post_link_product($format, $link, $in_same_cat, $excluded_categories, true);
}

function adjacent_post_link_product($format, $link, $in_same_cat = false, $excluded_categories = '', $previous = true) {
    if ($previous && is_attachment())
        $post = get_post(get_post()->post_parent);
    else
        $post = get_adjacent_post_product($in_same_cat, $excluded_categories, $previous);

    if (!$post) {
        $output = '';
    } else {
        $title = $post->post_title;

        if (empty($post->post_title))
            $title = $previous ? __('Previous Post') : __('Next Post');

        $title = apply_filters('the_title', $title, $post->ID);
        $date = mysql2date(get_option('date_format'), $post->post_date);
        $rel = $previous ? 'prev' : 'next';

        $string = '<a href="' . get_permalink($post) . '" rel="' . $rel . '">';
        $inlink = str_replace('%title', $title, $link);
        $inlink = str_replace('%date', $date, $inlink);
        $inlink = $string . $inlink . '</a>';

        $output = str_replace('%link', $inlink, $format);
    }

    $adjacent = $previous ? 'previous' : 'next';
    echo apply_filters("{$adjacent}_post_link", $output, $format, $link, $post);
}

function get_adjacent_post_product($in_same_cat = false, $excluded_categories = '', $previous = true) {
    global $wpdb;

    if (!$post = get_post())
        return null;

    $current_post_date = $post->post_date;

    $join = '';
    $posts_in_ex_cats_sql = '';
    if ($in_same_cat || !empty($excluded_categories)) {
        $join = " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";

        if ($in_same_cat) {
            if (!is_object_in_taxonomy($post->post_type, 'product_cat'))
                return '';
            $cat_array = wp_get_object_terms($post->ID, 'product_cat', array('fields' => 'ids'));
            if (!$cat_array || is_wp_error($cat_array))
                return '';
            $join .= " AND tt.taxonomy = 'product_cat' AND tt.term_id IN (" . implode(',', $cat_array) . ")";
        }

        $posts_in_ex_cats_sql = "AND tt.taxonomy = 'product_cat'";
        if (!empty($excluded_categories)) {
            if (!is_array($excluded_categories)) {
                // back-compat, $excluded_categories used to be IDs separated by " and "
                if (strpos($excluded_categories, ' and ') !== false) {
                    _deprecated_argument(__FUNCTION__, '3.3', sprintf(__('Use commas instead of %s to separate excluded categories.'), "'and'"));
                    $excluded_categories = explode(' and ', $excluded_categories);
                } else {
                    $excluded_categories = explode(',', $excluded_categories);
                }
            }

            $excluded_categories = array_map('intval', $excluded_categories);

            if (!empty($cat_array)) {
                $excluded_categories = array_diff($excluded_categories, $cat_array);
                $posts_in_ex_cats_sql = '';
            }

            if (!empty($excluded_categories)) {
                $posts_in_ex_cats_sql = " AND tt.taxonomy = 'product_cat' AND tt.term_id NOT IN (" . implode($excluded_categories, ',') . ')';
            }
        }
    }

    $adjacent = $previous ? 'previous' : 'next';
    $op = $previous ? '<' : '>';
    $order = $previous ? 'DESC' : 'ASC';

    $join = apply_filters("get_{$adjacent}_post_join", $join, $in_same_cat, $excluded_categories);
    $where = apply_filters("get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $posts_in_ex_cats_sql", $current_post_date, $post->post_type), $in_same_cat, $excluded_categories);
    $sort = apply_filters("get_{$adjacent}_post_sort", "ORDER BY p.post_date $order LIMIT 1");

    $query = "SELECT p.id FROM $wpdb->posts AS p $join $where $sort";
    $query_key = 'adjacent_post_' . md5($query);
    $result = wp_cache_get($query_key, 'counts');
    if (false !== $result) {
        if ($result)
            $result = get_post($result);
        return $result;
    }

    $result = $wpdb->get_var($query);
    if (null === $result)
        $result = '';

    wp_cache_set($query_key, $result, 'counts');

    if ($result)
        $result = get_post($result);

    return $result;
}

// get images size

function get_mthumb_link($sku, $size) {

    if (preg_match('/^VCN/', $sku)) {
        $title = 'vay-chong-nang-' . strtolower($sku);
    } else if (preg_match('/^ASM/', $sku)) {
        $title = 'ao-khoac-nu-' . strtolower($sku);
    } else if (preg_match('/^KK/', $sku)) {
        $title = 'dam-cong-so-' . strtolower($sku);
    } else if (preg_match('/^DH/', $sku)) {
        $title = 'dam-da-hoi-' . strtolower($sku);
    } else if (preg_match('/^PK/', $sku)) {
        $title = 'phu-kien-thoi-trang-' . strtolower($sku);
    } else if (preg_match('/^AKK/', $sku)) {
        $title = 'ao-khoac-khi-' . strtolower($sku);
    } else {
        // dnd, dd, dns, tx
    }

    $upload = wp_upload_dir();
    switch ($size) {
        case '500_750' : {
                $imgsrc = '/images/500_750/' . $title . '.jpg';
                if (file_exists($upload['basedir'] . $imgsrc)) {
                    $imgurl = $upload['baseurl'] . $imgsrc;
                } else {
                    $imgurl = $upload['baseurl'] . '/images/500_750/no_image.jpg';
                }
                break;
            }
        case '356_520' : {
                $imgsrc = '/images/356_520/' . $title . '.jpg';
                if (file_exists($upload['basedir'] . $imgsrc)) {
                    $imgurl = $upload['baseurl'] . $imgsrc;
                } else {
                    $imgurl = $upload['baseurl'] . '/images/356_520/no_image.jpg';
                }
                break;
            }
        case '180_263' : {
                $imgsrc = '/images/180_263/' . $title . '.jpg';
                if (file_exists($upload['basedir'] . $imgsrc)) {
                    $imgurl = $upload['baseurl'] . $imgsrc;
                } else {
                    $imgurl = $upload['baseurl'] . '/images/180_263/no_image.jpg';
                }
                break;
            }
        case '146_168' : {
                $imgsrc = '/images/146_168/' . $title . '.jpg';
                if (file_exists($upload['basedir'] . $imgsrc)) {
                    $imgurl = $upload['baseurl'] . $imgsrc;
                } else {
                    $imgurl = $upload['baseurl'] . '/images/146_168/no_image.jpg';
                }
                break;
            }
        case '134_134' : {
                $imgsrc = '/images/134_134/' . $title . '.jpg';
                if (file_exists($upload['basedir'] . $imgsrc)) {
                    $imgurl = $upload['baseurl'] . $imgsrc;
                } else {
                    $imgurl = $upload['baseurl'] . '/images/134_134/no_image.jpg';
                }
                break;
            }
        default : break;
    }

    return $imgurl;
}

function mysite_custom_search($query) {
    if ($query->is_search) {
        $query->set('post_type', 'product');
        $query->set('posts_per_page', 20);
    } return $query;
}

add_filter('pre_get_posts', 'mysite_custom_search');



add_filter('wp_title', 'my_title', 10, 2);

function my_title() {
    // Don't affect wp_title() calls in feeds.
    if (is_feed())
        return $title;

    // The $paged global variable contains the page number of a listing of posts.
    // The $page global variable contains the page number of a single post that is paged.
    // We'll display whichever one applies, if we're not looking at the first page.
    global $paged, $page;

    if (is_search()) {
        // If we're a search, let's start over:
        $title = sprintf(__('Search results for %s', 'Knerten'), '"' . get_search_query() . '"');
        // Add a page number if we're on page 2 or more:
        if ($paged >= 2)
            $title .= " $separator " . sprintf(__('Page %s', 'Knerten'), $paged);
        // Add the site name to the end:
        $title .= " $separator " . get_bloginfo('name', 'display');
        // We're done. Let's send the new title back to wp_title():
        return $title;
    }


    global $post;

    // If we have a site description and we're on the home/front page, add the description:
    $site_description = get_bloginfo('description', 'display');
    if (is_category()) {
        $cat = get_the_category();
        $title .= $cat[0]->name . " - " . $site_description;
        echo $title;
    }

    if (is_page() || is_single())
        $title .= $post->post_title . " - " . $site_description;

    if ($site_description && ( is_home() || is_front_page() ))
        $title .= " $separator " . $site_description;

    if (is_product()) {
        $get_sku = get_post_meta($post->ID, '_sku', true);
        $title = $post->post_title . " " . $get_sku . " | " . $site_description;
        echo $title;
        return;
    }
    // Add a page number if necessary:
    if ($paged >= 2 || $page >= 2)
        $title .= " $separator " . sprintf(__('Page %s', 'Knerten'), max($paged, $page));

    // Return the new title to wp_title():
    return $title;
}

